<script setup>
import { ref, reactive, nextTick } from 'vue'
import {
  Edit, Check, Close, Lock, Plus
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { changeAvatarApi } from '@/api/user'
import { useUserStore } from '@/stores'

// 是在使用仓库中数据的初始值 (无需响应式) 解构无问题
const {
  user: { email, id, nickname, username, phone, address, avatar },
  getUser
} = useUserStore()

// 用户信息数据
const userInfo = reactive({
  id,
  username,
  nickname,
  email,
  phone,
  address,
  avatar,
})
const isEditing = ref(false)
const passwordDialogVisible = ref(false)
const userForm = ref(null)


// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

// 密码表单验证规则
const passwordRules = reactive({
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
// 表单引用
const passwordFormRef = ref(null)

const originalUserInfo = JSON.parse(JSON.stringify(userInfo))

// 编辑信息
const handleEdit = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  Object.assign(userInfo, originalUserInfo)
}

// 提交表单
const submitForm = () => {
  userForm.value.validate((valid) => {
    if (valid) {
      // 这里应该是调用API保存数据的逻辑
      userInfo.username = 'test'

      ElMessage.success('保存成功')
      getUser()
      isEditing.value = false
      Object.assign(originalUserInfo, userInfo)
    } else {
      ElMessage.error('请检查输入')
      return false
    }
  })
}

const showChangePasswordDialog = () => {
  passwordDialogVisible.value = true
  // 正确调用表单组件的 resetFields 方法
  nextTick(() => {
    passwordFormRef.value?.resetFields()
  })
}

// 修改密码
const changePassword = () => {
  passwordFormRef.value.validate((valid) => {
    if (valid) {
      // 这里应该是调用API修改密码的逻辑
      console.log(passwordForm.oldPassword)
      console.log(passwordForm.newPassword)
      ElMessage.success('密码修改成功')
      passwordDialogVisible.value = false
    } else {
      ElMessage.error('请检查输入')
      return false
    }
  })
}

// 处理文件选择
const handleFileChange = async (uploadFile) => {
  // 验证文件
  if (!validateFile(uploadFile.raw)) return

  const loading = ElLoading.service({
    lock: true,
    text: '头像上传中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const formData = new FormData()
    formData.append('file', uploadFile.raw)

    const avatarUrl = await changeAvatarApi(formData)
    userInfo.avatar = avatarUrl.data.avatarUrl

    ElMessage.success('头像上传成功')
    getUser()
  } catch (error) {
    ElMessage.error(error.message || '头像上传失败')
  } finally {
    loading.close()
  }
}

// 文件验证
const validateFile = (file) => {
  const validTypes = ['image/jpeg', 'image/png', 'image/gif']
  const isImage = validTypes.includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

</script>

<template>
  <div class="user-profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>用户信息</h2>
        </div>
      </template>

      <div class="profile-content">
        <!-- 头像区域 -->
        <div class="avatar-section">
          <el-upload class="avatar-uploader" :show-file-list="false" :auto-upload="false" :on-change="handleFileChange"
            accept="image/jpeg,image/png,image/gif" :headers="uploadHeaders">
            <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
          <p>点击上传头像</p>
        </div>

        <!-- 用户信息表单 -->
        <el-form :model="userInfo" label-width="80px" :rules="rules" ref="userForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInfo.username" :disabled="!isEditing"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfo.email" :disabled="!isEditing"></el-input>
          </el-form-item>

          <el-form-item label="电话" prop="phone">
            <el-input v-model="userInfo.phone" :disabled="!isEditing"></el-input>
          </el-form-item>

          <el-form-item label="地址" prop="address">
            <el-input v-model="userInfo.address" :disabled="!isEditing"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleEdit" v-if="!isEditing">
              <el-icon>
                <Edit />
              </el-icon> 编辑信息
            </el-button>

            <el-button type="success" @click="submitForm" v-if="isEditing">
              <el-icon>
                <Check />
              </el-icon> 保存
            </el-button>

            <el-button @click="cancelEdit" v-if="isEditing">
              <el-icon>
                <Close />
              </el-icon> 取消
            </el-button>

            <el-button type="warning" @click="showChangePasswordDialog" style="margin-left: 20px">
              <el-icon>
                <Lock />
              </el-icon> 修改密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="30%">
      <el-form label-width="120px" :model="passwordForm" :rules="passwordRules" ref="passwordFormRef"
        style="width: 90%;padding-top: 30px;">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changePassword">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<style scoped>
.user-profile-container {
  width: 80%;
  margin: 20px auto;
}

.card-header {
  text-align: center;
}

.profile-content {
  display: flex;
  flex-wrap: wrap;
}

.avatar-section {
  width: 200px;
  text-align: center;
  margin-right: 40px;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
  margin: 0 auto 15px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.el-form {
  flex: 1;
  min-width: 300px;
}
</style>